package logic

import (
	"context"
	"luck/model/mysql"

	"luck/luckrpc/internal/svc"
	"luck/luckrpc/luckrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *luckrpc.ProductListRequest) (*luckrpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	offset := (in.Page - 1) * in.Size

	if in.Size < 10 {
		in.Size = 10
	}

	if in.Size > 100 {
		in.Size = 100
	}

	var products []mysql.Product
	sk := mysql.DB.Debug().Model(&mysql.Product{}).Offset(int(offset)).Limit(int(in.Size))
	//名称关键词
	if in.Name != "" {
		sk = sk.Where("name like ?", "%"+in.Name+"%")
	}
	//口味查询
	if in.TasTe != "" {
		sk = sk.Where("taste = ?", in.TasTe)
	}
	//价格排序
	if in.PriceOrder == 1 {
		sk = sk.Order("price desc")
	}

	if in.PriceOrder == 2 {
		sk = sk.Order("price asc")
	}
	//库存排序
	if in.StockOrder == 1 {
		sk = sk.Order("stock desc")
	}

	if in.StockOrder == 2 {
		sk = sk.Order("stock asc")
	}
	//价格区间查询
	if in.Start > 0 {
		sk = sk.Where("price>=?", in.Start)
	}

	if in.End > 0 {
		sk = sk.Where("price<=?", in.End)
	}

	sk.Find(&products)

	var productList []*luckrpc.ProductList

	for _, product := range products {
		list := luckrpc.ProductList{
			Name:       product.Name,
			Price:      float32(product.Price),
			Stock:      product.Stock,
			Ingredient: product.Ingredient,
			Taste:      product.Taste,
			Status:     product.Status,
			ImageUrl:   product.ImageUrl,
			CategoryId: product.CategoryId,
			ProductId:  int64(product.ID),
		}
		productList = append(productList, &list)
	}

	return &luckrpc.ProductListResponse{
		List: productList,
	}, nil
}
